<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2019~2022 https://www.meoyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 喵云科技 【https://www.meoyun.com】
// +----------------------------------------------------------------------


namespace app\api\controller;

use app\common\service\BaseService;
use app\common\service\Token;
use app\common\service\Wechat;
use app\api\service\User as UserService;
use app\common\model\User as UserModel;
use think\facade\Db;

class User extends ApiBase
{

    //用户列表
    public function list()
    {
        $list = UserModel::getList();
        return message($list);
    }

    //微信小程序登录
    public function miniProgramLogin()
    {
        $param = input('post.');
        $wechat = new Wechat();
        $userService = new UserService();
        $api = $wechat->MiniApp->getClient();

        $response = $api->get('/sns/jscode2session', [
            "appid" => $wechat->MiniApp->getConfig()['app_id'],
            "secret" => $wechat->MiniApp->getConfig()['secret'],
            "js_code" => $param["code"],
            'grant_type' => 'authorization_code'
        ]);

        $responseData = $response->toArray();

        //如果正确获取到用户openid，则执行登录操作
        if (isset($responseData['openid'])) {
            $param["openid"] = $responseData['openid'];
            $user = $userService->createOrGetLoginUser('openid', $responseData['openid'], $param);
            return message($user, "登录成功");
        } else {
            return json($responseData);
        }
    }

    //搜索
    public function search()
    {
        $keyword = input("keyword");
        $where[] = ["username", "like", "%$keyword%"];
        $list = UserModel::getList($where);
        return message($list);
    }

    //当前登录用户信息
    public function currentUserInfo()
    {
        $userId = BaseService::getLoginUserId();

        $user = UserModel::find($userId);

        $UserService = new UserService();
        $user = $UserService->userExtendInfo($user);
        $user["token"] = BaseService::buildToken(["userId" => $user["id"]]);

        return message($user);
    }

    //根据userId获取用户信息
    public function userInfoById()
    {
        $userId = input("user_id");

        $user = UserModel::find($userId);

        $UserService = new UserService();
        $user = $UserService->userExtendInfo($user);

        return message($user);
    }

    //添加关注
    public function addFollow()
    {
        $followUserId = input("user_id");
        $loginUserId = BaseService::getLoginUserId();

        if ($followUserId == $loginUserId) {
            return error("不能关注自己");
        }

        $find = Db::name("follow")->where(["user_id" => $loginUserId, "follow_uid" => $followUserId])->find();

        if ($find) {
            return error("请勿重复关注");
        }

        $res = Db::name("follow")->insert(["user_id" => $loginUserId, "follow_uid" => $followUserId, "create_time" => time()]);
        $username = Db::name("user")->where("id", $loginUserId)->value("username");

        if ($res) {
            \app\common\service\Message::send($loginUserId, $followUserId, 0, 4, "【" . $username . "】关注了你");
            return message("关注成功");
        }

        return error("关注失败");
    }

    //取消关注
    public function cancelFollow()
    {
        $followUserId = input("user_id");
        $loginUserId = BaseService::getLoginUserId();

        $where["user_id"] = $loginUserId;
        $where["follow_uid"] = $followUserId;
        $res = Db::name("follow")->where($where)->delete();
        if ($res) {
            return message("已取消关注");
        }
        return error("错误");
    }

    //登录用户粉丝列表
    public function userFans()
    {
        $userId = BaseService::getLoginUserId();
        $list = Db::name("follow")->where("follow_uid", $userId)->order("create_time desc")->paginate(20)->each(function ($item) use ($userId) {
            $user = UserModel::where("id", $item["user_id"])->find();

            $where["user_id"] = $userId;
            $where["follow_uid"] = $user["uid"];

            $res1 = Db::name("follow")->where($where)->find();

            if ($res1) {
                $user["has_follow"] = 1; //互相关注
            } else {
                $user["has_follow"] = 0; //未关注
            }

            return $user;
        });

        return message($list);
    }

    //登录用户关注列表
    public function follow()
    {
        $userId = BaseService::getLoginUserId();
        $followUids = Db::name("follow")->where("user_id", $userId)->column("follow_uid");
        $list = UserModel::where("id", "in", $followUids)->withoutField("password,email,group_id,openid,status,user_type,create_time")->paginate(10)->each(function ($item) use ($userId) {
            $where["user_id"] = $item["id"];
            $where["follow_uid"] = $userId;

            $res1 = Db::name("follow")->where($where)->find();

            if ($res1) {
                $item["has_follow"] = 1; //互相关注
            } else {
                $item["has_follow"] = 2; //已关注
            }

            return $item;
        });
        return message($list);
    }

    //用户修改信息
    public function userInfoEdit()
    {
        $data = input("post.");
        $userId = BaseService::getLoginUserId();
        $data["id"] = $userId;

        if (!empty($data["username"])) {
            $user = Db::name("user")->where("id", $userId)->find();

            if ($user["username"] == $data["username"]) {
                return error("用户昵称已存在");
            }
        }

        $res = UserModel::update($data);
        if ($res) {

            $userInfo = UserModel::withoutField("group_id,create_time")->where("id", $userId)->find();
            $userInfo["token"] = BaseService::buildToken(["id" => $userId]);

            $userService = new UserService();
            $userInfo = $userService->userExtendInfo($userInfo);

            return message($userInfo, "修改成功");
        }
        return error("修改失败");
    }
}